package com.eastfair.weixin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.projectcore.api.ProjectCoreServiceFeign;import com.eastfair.core.snowflake.DefaultUidGenerator;
import com.eastfair.weixin.dao.OfficialEventMapper;
import com.eastfair.weixin.entity.OfficialEvent;
import com.eastfair.weixin.service.OfficialEventService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 业务实现类
 * 微信公众号事件
 * </p>
 *
 * @author ligang
 * @date 2021-09-06
 */
@Slf4j
@Service
public class OfficialEventServiceImpl extends SuperServiceImpl<OfficialEventMapper, OfficialEvent> implements OfficialEventService {

    @Autowired
    ProjectCoreServiceFeign projectCoreServiceFeign;

    /**************sharding 分库分表操作 *****************/
    @Override
    public boolean updateByIdOfShard(OfficialEvent entity) {
        UpdateWrapper<OfficialEvent> updateWrapper = new UpdateWrapper<>();
        //可将指定字段更新为null
        updateWrapper.lambda().eq(OfficialEvent::getProjectId, entity.getProjectId()).eq(OfficialEvent::getId,entity.getId());
        entity.setProjectId(null);
        //删除缓存
        return SqlHelper.retBool(this.getBaseMapper().update(entity, updateWrapper));
    }

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(OfficialEvent model) {
        //雪花ID
        if(model.getProjectId()!=null){
            model.setId(DefaultUidGenerator.getUidOfProjectId(model.getProjectId()));
            model.setProjectId(model.getProjectId());
        }else{
            model.setId(DefaultUidGenerator.getUidOfProjectId(ContextUtil.getProjectId()));
            model.setProjectId(ContextUtil.getProjectId());
        }
        return R.successDef();
    }



    @Override
    public R subscribe(Map<String, String> xmlMap) {
        String eventKey = xmlMap.get("eventkey");
        String event = xmlMap.get("event");
        String ticket = xmlMap.get("ticket");
        String openId = xmlMap.get("fromusername");
        if(StringUtils.isNotBlank(eventKey)){
            eventKey = eventKey.substring(eventKey.indexOf("qrscene_"));
            JSONObject jsonObject = JSONObject.parseObject(eventKey);
            Long userId = jsonObject.getLong("userId");
            Long projectId = jsonObject.getLong("projectId");
            if(userId != null){
                //查询是否重复
                OfficialEvent queryofficialEvent = new OfficialEvent();
                queryofficialEvent.setUserAccountId(userId);
                queryofficialEvent.setEvent(event);
                queryofficialEvent.setProjectId(projectId);
                List<OfficialEvent> officialEventList = list(queryofficialEvent,null);
                if(officialEventList!=null && !officialEventList.isEmpty()){
                    //已存在
                    return R.success();
                }
            }
            //新增
            OfficialEvent officialEvent = new OfficialEvent();
            officialEvent.setOpenid(openId);
            officialEvent.setEvent(event);
            officialEvent.setEventKey(jsonObject.toJSONString());
            officialEvent.setTicket(ticket);
            officialEvent.setUserAccountId(userId);
            save(officialEvent);
        }
        return R.success();
    }

    @Override
    public R unsubscribe(Map<String, String> xmlMap) {
        String event = xmlMap.get("event");
        String ticket = xmlMap.get("ticket");
        String openId = xmlMap.get("fromusername");
        //查询是否重复
        OfficialEvent queryofficialEvent = new OfficialEvent();
        queryofficialEvent.setOpenid(openId);
        queryofficialEvent.setEvent(event);
        List<OfficialEvent> officialEventList = list(queryofficialEvent,null);
        if(officialEventList!=null && !officialEventList.isEmpty()){
            //已存在
            return R.success();
        }
        //新增
        OfficialEvent officialEvent = new OfficialEvent();
        officialEvent.setOpenid(openId);
        officialEvent.setEvent(event);
        officialEvent.setTicket(ticket);
        save(officialEvent);
        return R.success();
    }

    @Override
    public List<OfficialEvent> list(OfficialEvent officialEvent, List<Long> ids) {
        //查询
        QueryWrapper<OfficialEvent> queryWrapper = new QueryWrapper<>();
        if (officialEvent != null) {
            if (officialEvent.getUserAccountId() != null) {
                queryWrapper.lambda().eq(OfficialEvent::getUserAccountId, officialEvent.getUserAccountId());
            }
            if (officialEvent.getId() != null) {
                queryWrapper.lambda().eq(OfficialEvent::getId, officialEvent.getId());
            }
            if (StringUtils.isNotBlank(officialEvent.getEvent())) {
                queryWrapper.lambda().eq(OfficialEvent::getEvent, officialEvent.getEvent());
            }
        }
        if (ContextUtil.getProjectId() != null) {
            queryWrapper.lambda().eq(OfficialEvent::getProjectId, ContextUtil.getProjectId());
        }
        if (officialEvent.getProjectId() != null) {
            queryWrapper.lambda().eq(OfficialEvent::getProjectId, officialEvent.getProjectId());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(OfficialEvent::getId, ids);
        }
        queryWrapper.lambda().eq(OfficialEvent::getIsDeleted, BusinessConstant.DELETE_NO);
        return list(queryWrapper);
    }
}
